package com.catietie.bookmanagement.service.Impl;


import com.catietie.bookmanagement.dao.mapper.UserMapper;
import com.catietie.bookmanagement.dao.pojo.User;
import com.catietie.bookmanagement.dto.req.UserLoginReqDTO;
import com.catietie.bookmanagement.dto.resp.UserLoginRespDTO;
import com.catietie.bookmanagement.service.UserService;
import com.catietie.bookmanagement.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {


    private final UserMapper userMapper;

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        String username = userLoginReqDTO.getUsername();
        User user = userMapper.selectByUsername(username);
        if (Objects.isNull(user)) {
            return null;
        }
        if (!user.getPassword().equals(userLoginReqDTO.getPassword())) {
            return null;
        }
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("user", user.getUsername());
        String token = JwtUtil.createJWT(claims);
        return UserLoginRespDTO.builder()
                .username(username)
                .token(token)
                .build();
    }
}
